import React, { useEffect, useRef, useState } from "react";
import { useNavigate, useLocation } from "react-router-dom";
import { NavBar, Toast } from "antd-mobile";
import { Html5Qrcode } from "html5-qrcode";
import "./style.scss";
import $fetch from "../../../utils/app/$fetch";
import { log } from "console";

// 该扫一扫功能只能在https环境下或者本地调试使用

const ScanComponent = () => {
  const location: any = useLocation();
  const navigate = useNavigate();
  const detail: any = location?.state?.detail;
  const from = detail?.from;
  const title = detail?.title
  const a: any = useRef(null);

  useEffect(() => {
    getCameras();
    return () => {
      a.current.stop();
    };
  }, []);

  const callBack = async(decodedText: any, decodedResult: any) => {
    try {
      
   
    if (from === "online") {
      const { goodsId, timingDuration, goodsName } = decodedText
        .split("&")
        .reduce((acc: any, param: any) => {
          const [key, value] = param.split("=");
          acc[key] = value;
          return acc;
        }, {});

      navigate("/activity/timing", {
        state: {
          detail: { ...detail, goodsId, timingDuration, goodsName },
        },
      });
    } else if (from === "offline") {
      const { orderSn, goodsId } = decodedText
        .split("&")
        .reduce((acc: any, param: any) => {
          const [key, value] = param.split("=");
          acc[key] = value;
          return acc;
        }, {});
      await $fetch(`operation/exchangeOffline/${goodsId}?orderSn=${orderSn}`, {}, {method: 'post', noGroupId: 'no'});
      navigate("/activity/list");
    }
    // $fetch(`/operation/verifyTicket/${customerId}/${decodedText}`)
  } catch (error) {
      console.log(error,'_____error')
  }
  };

  const getCameras = () => {
    Html5Qrcode.getCameras()
      .then((devices) => {
        if (devices && devices.length) {
          let cameraId = devices[0].id; // 前置摄像头
          a.current = new Html5Qrcode("reader");
          a.current
            .start(
              // environment后置摄像头 user前置摄像头
              { facingMode: "environment" },

              // cameraId,
              {
                fps: 10,
                qrbox: { width: 300, height: 300 },
              },
              callBack,
              (errorMessage: any) => {
                // a.current.stop();
                // 失败做什么
              }
            )
            .catch((err: any) => {
              console.log("扫码错误信息", err);
              // 错误信息处理仅供参考，具体情况看输出！！！
              if (typeof err == "string") {
                Toast.show(err);
              } else {
                if (err.name == "NotAllowedError")
                  return Toast.show("您需要授予相机访问权限");
                if (err.name == "NotFoundError")
                  return Toast.show("这个设备上没有摄像头");
                if (err.name == "NotSupportedError")
                  return Toast.show(
                    "摄像头访问只支持在安全的上下文中，如https或localhost"
                  );
                if (err.name == "NotReadableError")
                  return Toast.show("相机被占用");
                if (err.name == "OverconstrainedError")
                  return Toast.show("安装摄像头不合适");
                if (err.name == "StreamApiNotSupportedError")
                  return Toast.show("此浏览器不支持流API");
              }
            });
        }
      })
      .catch((err) => {
        console.log(err, "______err");

        Toast.show("您需要授予相机访问权限！");
      });
  };

  const back = () => {
    window.history.go(-2);
    // navigate("/activity/choose", {state: { detail: { ...detail }}});
  };

  return (
    <div className="reader_box">
      <NavBar
        style={{
          "--border-bottom": "1px #eee solid",
        }}
        onBack={() => back()}
      >
        {title}
      </NavBar>
      <div
        id="reader"
        className="reader"
        style={{ width: "600px", backgroundColor: "gray" }}
      ></div>
    </div>
  );
};

export default ScanComponent;